package com.heba.fragment.scan;

import android.graphics.Typeface;
import android.os.Bundle;

import androidx.annotation.Dimension;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.OrientationHelper;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.google.gson.Gson;
import com.heba.Cfg;
import com.heba.adapter.ItemComparisonAdapter;
import com.heba.bean.PhotoObject;
import com.heba.bean.category.OptionLevel3Object;
import com.heba.bean.product.ItemProductCompareObject;
import com.heba.bean.product.ItemProductDetailInfoObject;
import com.heba.bean.product.ItemProductInfoObject;
import com.heba.bean.product.ProductCategory;
import com.heba.bean.product.ProductContentObject;
import com.heba.bean.product.ProductTag;
import com.heba.config.CommonConfig;
import com.heba.event.MessageEvent;
import com.heba.fragment.BaseFragment;
import com.heba.fragment.LazyFragment;
import com.heba.fragment.business.MineSelectBusinessFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.ZoomPhotoActivity;
import com.heba.greenmulu.product.MineSelectBusinessActivity;
import com.heba.greenmulu.scan.ItemFeatureActivity;
import com.heba.greenmulu.scan.ItemProductDetailActivity;
import com.heba.greenmulu.scan.ItemProductOptionCategoryActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.CommonUtils;
import com.heba.utils.DensityUtils;
import com.heba.utils.GlideUtil;
import com.heba.utils.IndicatorLineUtil;
import com.heba.utils.ToastShow;
import com.heba.view.FlowLayout;
import com.loopj.android.http.RequestParams;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

/**
 * 產品營養頁面
 * Created by jason on 2020/1/15.
 */
public class ProductNutritionFragment extends LazyFragment {

    private RefreshLayout refreshLayout;
    private RecyclerView recyclerView;
    private ItemComparisonAdapter adapter;

    private boolean isFirstHeader;    //用于判断刷新头部
    private boolean isFirstSpinner;    //用于判断刷新头部的spinner，防止重复刷新数据
    private List<ItemProductCompareObject> headerList = new ArrayList<>();    //扫描列表，可能有大包装会存在多条信息
    private ItemProductCompareObject headerItemProductCompareObject = new ItemProductCompareObject();
    private List<ItemProductCompareObject> list = new ArrayList<>();
    private String productID = "";
    private String barCode = "";
    private ItemProductDetailInfoObject itemProductDetailInfoObject;
    private ItemProductInfoObject infoObject;
    //产品比较参数
    private int type = 2;    //1表示比较 Per Serving, 2表示比较 Per 100g/ml, 3表示比较 Whole Pack
    private int isEnergy = 0;
    private int isProtein = 0;
    private int isFat = 0;
    private int isSatFat = 0;
    private int isCarb = 0;
    private int isSugar = 0;
    private int isSodium = 0;

    private String optionIds = "";  //传递筛选的id，获取相关产品数据

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected void lazyLoad() {
        getProductContentData();

    }

    /**
     * 傳遞參數
     *
     * @param productID
     * @param barCode
     * @return
     */
    public static ProductNutritionFragment newInstance(String productID, String barCode) {
        ProductNutritionFragment fragment = new ProductNutritionFragment();
        Bundle bundle = new Bundle();
        bundle.putString(CommonConfig.PRODUCT_ID, productID);
        bundle.putString(CommonConfig.BARCODE, barCode);
        fragment.setArguments(bundle);
        return fragment;
    }

    /**
     * 取出参数
     */
    private void parseArgument() {
        Bundle bundle = getArguments();
        productID = bundle.getString(CommonConfig.PRODUCT_ID, "");
        barCode = bundle.getString(CommonConfig.BARCODE, "");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_scan_product_nutrition, container, false);
        parseArgument();
        init();
        getProductInfoObject(view);
        return view;
    }

    /**
     * 初始化
     */
    private void init() {
        isFirstHeader = true;
        isFirstSpinner = true;
        Cfg.getProductRecord();
        isEnergy = Cfg.isEnergy;
        isProtein = Cfg.isProtein;
        isFat = Cfg.isFat;
        isSatFat = Cfg.isSatFat;
        isCarb = Cfg.isCarb;
        isSugar = Cfg.isSugar;
        isSodium = Cfg.isSodium;
    }

    /**
     * 多包装时，下拉选择产品
     */
    private void addSpinnerData(Spinner mSpinner) {
        //原始string数组
        final String[] spinnerItems = new String[headerList.size()];
        if (!headerList.isEmpty()) {
            for (int i = 0; i < headerList.size(); i++) {
                spinnerItems[i] = headerList.get(i).getFlavorName();
            }
        }

        //简单的string数组适配器：样式res，数组
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<>(getActivity(),
                android.R.layout.simple_spinner_item, spinnerItems);
        //下拉的样式res
        spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //绑定 Adapter到控件
        mSpinner.setAdapter(spinnerAdapter);
        //选择监听
        mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {
                //设置spinner内的填充文字居中
//                ((TextView) view).setGravity(Gravity.CENTER);
                headerItemProductCompareObject = headerList.get(pos);
                getProductSimilarData(headerItemProductCompareObject.getProductID());
                isFirstHeader = true;
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }

    /**
     * initView
     *
     * @param view
     */
    private void initView(View view) {
        refreshLayout = view.findViewById(R.id.refreshLayout);
        recyclerView = view.findViewById(R.id.recyclerView);

        adapter = new ItemComparisonAdapter(getActivity(), list) {
            @Override
            public void convert(RecyclerView.ViewHolder holder, ItemProductCompareObject data, int position) {
                if (holder instanceof HeaderHolder) {
                    if (isFirstHeader) {
                        isFirstHeader = false;
                        HeaderHolder headerHolder = (HeaderHolder) holder;
                        if (null != headerItemProductCompareObject) {
                            if (!headerList.isEmpty() && headerList.size() == 1) {
                                headerHolder.spinner.setVisibility(View.GONE);
                            } else {
                                if (isFirstSpinner) {
                                    isFirstSpinner = false;
                                    headerHolder.spinner.setVisibility(View.VISIBLE);
                                    addSpinnerData(headerHolder.spinner);
                                }
                            }
                            if (infoObject != null) {
                                List<String> contents = new ArrayList<>();
                                //添加分类
                                if (infoObject.getCategoryNav() != null) {
                                    if (!infoObject.getCategoryNav().getName1().isEmpty()) {
                                        contents.add(calculateCategoryString(infoObject.getCategoryNav()));
                                    } else {
                                        contents.add("");
                                    }
                                }

                                //添加原产地/包装地
                                contents.add("");

                                //口味
                                contents.add("");

                                //标签
//                                contents.add("");

                                //成分
                                contents.add(infoObject.getIngredient());

                                //致敏源
                                contents.add("");

                                //其他
                                contents.add(infoObject.getRemark());

                                //显示产品名称等信息
                                showProductHeaderData(infoObject);

                                //显示产品详细规格
                                setTitleTextView(headerHolder,contents,infoObject);
                            }
                            //添加产品信息
//                            GlideUtil.loadImageWithDefaultPlaceHolder(getActivity(), headerItemProductCompareObject.getIcon(), headerHolder.img_photo);
//                            headerHolder.txt_title.setText(headerItemProductCompareObject.getBrandName());
//                            headerHolder.txt_content.setText(headerItemProductCompareObject.getProductName());
//                            headerHolder.txt_serving_size.setText(String.format(getResources().getString(R.string.per_serving_size), headerItemProductCompareObject.
//                                    getPackageSize(), headerItemProductCompareObject.getPackageUnit(), CommonUtils.subZeroAndDot(headerItemProductCompareObject.getServingSize()), headerItemProductCompareObject.getServingSizeUnit()));
//                            headerHolder.img_collect.setSelected(headerItemProductCompareObject.getIsCollect() == 1 ? true : false);

                            /**
                             * 添加tab
                             */
                            headerHolder.tabLayout.removeAllTabs();
                            headerHolder.tabLayout.clearOnTabSelectedListeners();

                            //tab标签
                            String[] strings = getResources().getStringArray(R.array.array_per);
                            for (int i = 0; i < strings.length; i++) {
                                headerHolder.tabLayout.addTab(headerHolder.tabLayout.newTab().setText(strings[i]));
                            }

                            /**
                             * 设置指示线长度间隔(单位dp)
                             */
                            headerHolder.tabLayout.post(new Runnable() {
                                @Override
                                public void run() {
                                    IndicatorLineUtil.setIndicator(headerHolder.tabLayout, 0, 0);
                                }
                            });

                            /**
                             * 默认选中第二个选项卡
                             */
                            headerHolder.tabLayout.getTabAt(1).select();
                            updatePerView(headerHolder.linear_per_view, headerItemProductCompareObject.getPergmlObject(), type, Float.valueOf(headerItemProductCompareObject.getServingSize()),
                                    Float.valueOf(headerItemProductCompareObject.getPackageSize()), headerItemProductCompareObject.isFood());

                            /**
                             * 监听tablayout
                             */
                            headerHolder.tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
                                @Override
                                public void onTabSelected(TabLayout.Tab tab) {
                                    switch (tab.getPosition()) {
                                        case 0:
                                            type = 1;
                                            updatePerView(headerHolder.linear_per_view, headerItemProductCompareObject.getPerServingObject(), type, Float.valueOf(headerItemProductCompareObject.getServingSize()),
                                                    Float.valueOf(headerItemProductCompareObject.getPackageSize()), headerItemProductCompareObject.isFood());
                                            getProductSimilarData(headerItemProductCompareObject.getProductID());
                                            break;
                                        case 1:
                                            type = 2;
                                            updatePerView(headerHolder.linear_per_view, headerItemProductCompareObject.getPergmlObject(), type, Float.valueOf(headerItemProductCompareObject.getServingSize()),
                                                    Float.valueOf(headerItemProductCompareObject.getPackageSize()), headerItemProductCompareObject.isFood());
                                            getProductSimilarData(headerItemProductCompareObject.getProductID());
                                            break;
                                        case 2:
                                            type = 3;
                                            updatePerView(headerHolder.linear_per_view, headerItemProductCompareObject.getWholePackObject(), type, Float.valueOf(headerItemProductCompareObject.getServingSize()),
                                                    Float.valueOf(headerItemProductCompareObject.getPackageSize()), headerItemProductCompareObject.isFood());
                                            getProductSimilarData(headerItemProductCompareObject.getProductID());
                                            break;
                                        default:
                                            break;
                                    }
                                }

                                @Override
                                public void onTabUnselected(TabLayout.Tab tab) {

                                }

                                @Override
                                public void onTabReselected(TabLayout.Tab tab) {

                                }
                            });

                            /**
                             * 查看大图
                             */
//                            headerHolder.img_photo.setOnClickListener(v -> {
//                                if (!headerItemProductCompareObject.getProductImageList().isEmpty()) {
//                                    Bundle bundle1 = new Bundle();
//                                    bundle1.putSerializable(CommonConfig.PHOTOLIST, (Serializable) headerItemProductCompareObject.getProductImageList());
//                                    openActivityWithFadeInAnimation(ZoomPhotoActivity.class, bundle1);
//                                }
//                            });

                            /**
                             * 分享
                             */
//                            headerHolder.img_share.setOnClickListener(v -> {
//                                /**
//                                 * 调用系统分享
//                                 */
//                                Intent shareIntent = new Intent(Intent.ACTION_SEND);
//                                shareIntent.setType("text/*");
////                                shareIntent.putExtra(Intent.EXTRA_SUBJECT, getResources().getString(R.string.share));//添加分享内容标题
//                                shareIntent.putExtra(Intent.EXTRA_TEXT, headerItemProductCompareObject.getProductName() + " " + headerItemProductCompareObject.getLink());  //添加分享内容
//                                startActivity(Intent.createChooser(shareIntent, getResources().getString(R.string.share)));
//                            });

                            /**
                             * 产品对比参数选择
                             */
                            headerHolder.txt_less_energy.setSelected(isEnergy != 0);
                            headerHolder.txt_more_protein.setSelected(isProtein != 0);
                            headerHolder.txt_less_fat.setSelected(isFat != 0);
                            headerHolder.txt_less_sat_fat.setSelected(isSatFat != 0);
                            headerHolder.txt_less_carb.setSelected(isCarb != 0);
                            headerHolder.txt_less_sugar.setSelected(isSugar != 0);
                            headerHolder.txt_less_sodium.setSelected(isSodium != 0);

                            /**
                             * 各种营养筛选点击处理
                             */
                            headerHolder.txt_less_energy.setOnClickListener(v -> {
                                headerHolder.txt_less_energy.setSelected(!headerHolder.txt_less_energy.isSelected());
                                isEnergy = headerHolder.txt_less_energy.isSelected() ? 1 : 0;
                                getProductSimilarData(headerItemProductCompareObject.getProductID());
                            });

                            headerHolder.txt_more_protein.setOnClickListener(v -> {
                                headerHolder.txt_more_protein.setSelected(!headerHolder.txt_more_protein.isSelected());
                                isProtein = headerHolder.txt_more_protein.isSelected() ? 1 : 0;
                                getProductSimilarData(headerItemProductCompareObject.getProductID());
                            });

                            headerHolder.txt_less_fat.setOnClickListener(v -> {
                                headerHolder.txt_less_fat.setSelected(!headerHolder.txt_less_fat.isSelected());
                                isFat = headerHolder.txt_less_fat.isSelected() ? 1 : 0;
                                getProductSimilarData(headerItemProductCompareObject.getProductID());
                            });

                            headerHolder.txt_less_sat_fat.setOnClickListener(v -> {
                                headerHolder.txt_less_sat_fat.setSelected(!headerHolder.txt_less_sat_fat.isSelected());
                                isSatFat = headerHolder.txt_less_sat_fat.isSelected() ? 1 : 0;
                                getProductSimilarData(headerItemProductCompareObject.getProductID());
                            });

                            headerHolder.txt_less_carb.setOnClickListener(v -> {
                                headerHolder.txt_less_carb.setSelected(!headerHolder.txt_less_carb.isSelected());
                                isCarb = headerHolder.txt_less_carb.isSelected() ? 1 : 0;
                                getProductSimilarData(headerItemProductCompareObject.getProductID());
                            });

                            headerHolder.txt_less_sugar.setOnClickListener(v -> {
                                headerHolder.txt_less_sugar.setSelected(!headerHolder.txt_less_sugar.isSelected());
                                isSugar = headerHolder.txt_less_sugar.isSelected() ? 1 : 0;
                                getProductSimilarData(headerItemProductCompareObject.getProductID());
                            });

                            headerHolder.txt_less_sodium.setOnClickListener(v -> {
                                headerHolder.txt_less_sodium.setSelected(!headerHolder.txt_less_sodium.isSelected());
                                isSodium = headerHolder.txt_less_sodium.isSelected() ? 1 : 0;
                                getProductSimilarData(headerItemProductCompareObject.getProductID());
                            });

                            /**
                             * 一般筛选事件处理
                             */
                            updateFilterCategoryView(headerHolder.linear_option_filter_view, headerItemProductCompareObject.getOptionLevel3ObjectList());

                            headerHolder.img_filter.setOnClickListener(v -> {
                                Bundle bundle = new Bundle();
                                bundle.putInt(CommonConfig.CATEGORY_ID, headerItemProductCompareObject.getCategoryid());
                                bundle.putInt(CommonConfig.CATEGORY_LEVEL, headerItemProductCompareObject.getCategorylevel());
                                openActivity(ItemProductOptionCategoryActivity.class, bundle);
                            });

                        }
                    }
                } else if (holder instanceof ItemHolder) {
                    ItemHolder itemHolder = (ItemHolder) holder;
                    itemHolder.constrain_view.setVisibility(View.VISIBLE);
                    itemHolder.constrain_view1.setVisibility(View.GONE);
                    GlideUtil.loadImageWithDefaultPlaceHolder(getActivity(), data.getIcon(), itemHolder.img_photo);
                    GlideUtil.loadImageWithDefaultPlaceHolder(getActivity(), data.getIcon(), itemHolder.img_photo1);
                    itemHolder.txt_product.setText(data.getBrandName());
                    itemHolder.txt_product1.setText(data.getBrandName());
                    itemHolder.txt_content.setText(data.getProductName());
                    itemHolder.txt_content1.setText(data.getProductName());
                    itemHolder.txt_serving_size.setText(String.format(getResources().getString(R.string.per_serving_size), data.
                            getPackageSize(), data.getPackageUnit(), CommonUtils.subZeroAndDot(data.getServingSize()), data.getServingSizeUnit()));
//                    itemHolder.img_collect.setSelected(data.getIsCollect() == 1 ? true : false);

                    /**
                     * 加载含量，此方法过于耗时
                     */
                    updatePerView(itemHolder.linear_per_view, data.getPergmlObject(), type, Float.valueOf(data.getServingSize()),
                            Float.valueOf(data.getPackageSize()), headerItemProductCompareObject.isFood());

                    /**
                     * 查看大图
                     */
                    itemHolder.img_photo1.setOnClickListener(v -> {
                        if (!data.getProductImageList().isEmpty()) {
                            Bundle bundle1 = new Bundle();
                            bundle1.putSerializable(CommonConfig.PHOTOLIST, (Serializable) data.getProductImageList());
                            openActivityWithFadeInAnimation(ZoomPhotoActivity.class, bundle1);
                        }
                    });

                    /**
                     * 前往產品頁面
                     */
                    itemHolder.txt_product_go.setOnClickListener(v -> {
                        Bundle bundle = new Bundle();
                        bundle.putString(CommonConfig.PRODUCT_ID, data.getProductID());
                        openActivity(ItemProductDetailActivity.class, bundle);
                    });

                    /**
                     * 显示大布局
                     */
                    itemHolder.constrain_view.setOnClickListener(v -> {
                        itemHolder.constrain_view.setVisibility(View.GONE);
                        itemHolder.constrain_view1.setVisibility(View.VISIBLE);
                    });

                    /**
                     * 显示小布局
                     */
                    itemHolder.constrain_view1.setOnClickListener(v -> {
                        itemHolder.constrain_view.setVisibility(View.VISIBLE);
                        itemHolder.constrain_view1.setVisibility(View.GONE);
                    });
                }
            }
        };
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        //设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
        //设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        //设置Adapter
        recyclerView.setAdapter(adapter);
        recyclerView.setItemViewCacheSize(30);
        recyclerView.setDrawingCacheEnabled(true);
        recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);

        /**
         * 增加额外缓存空间
         * 显示范围之外，应该额外缓存的空间
         */
        new LinearLayoutManager(getActivity()) {
            @Override
            protected int getExtraLayoutSpace(RecyclerView.State state) {
                return 200;
            }
        };

        //设置是否监听滚动到底部是触发自动刷新
        refreshLayout.setEnableAutoLoadMore(false);
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableLoadMore(false);

        /**
         * 处理下拉刷新事件
         */
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
                Page = 1;
                isRefreshFromTop = true;
            }
        });

        /**
         * 处理上拉加载事件
         */
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
                Page++;
                isRefreshFromTop = false;
            }
        });
    }

    /**
     * 比較營養素含量，顯示紅綠燈等級
     *
     * @param linearLayout  view
     * @param contentObject 含量數據,用於比較
     * @param type          1:每食用分量  2:每100g/ml  3:整個包裝
     * @param servingSize   食用分量
     * @param packageSize   整個包裝
     * @param isFood        食物还是饮料(所含标准不同)
     */
    private void updatePerView(LinearLayout linearLayout, ProductContentObject contentObject, int type, float servingSize, float packageSize, boolean isFood) {
        linearLayout.removeAllViews();
        /**
         * 計算含量標準
         */
        double fat = 0.0d, satFat = 0.0d, sugar = 0.0d, sodium = 0.0d;
        switch (type) {
            case 1:
                if (servingSize != 0) {
                    fat = (100 / servingSize) * contentObject.getFat();
                    satFat = (100 / servingSize) * contentObject.getSatFat();
                    sugar = (100 / servingSize) * contentObject.getSugar();
                    sodium = (100 / servingSize) * contentObject.getSodium();
                }
                break;
            case 2:
                fat = contentObject.getFat();
                satFat = contentObject.getSatFat();
                sugar = contentObject.getSugar();
                sodium = contentObject.getSodium();
                break;
            case 3:
                if (packageSize != 0) {
                    fat = (100 / packageSize) * contentObject.getFat();
                    satFat = (100 / packageSize) * contentObject.getSatFat();
                    sugar = (100 / packageSize) * contentObject.getSugar();
                    sodium = (100 / packageSize) * contentObject.getSodium();
                }
                break;
            default:
                break;
        }

        /**
         * 添加營養桶
         */
        for (int i = 0; i < 7; i++) {
            View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_per_image, null);
            ImageView imageView = view.findViewById(R.id.img_per_bg);
            TextView txt_text1 = view.findViewById(R.id.txt_text1);
            TextView txt_text2 = view.findViewById(R.id.txt_text2);
            TextView txt_text3 = view.findViewById(R.id.txt_text3);
            TextView txt_unit = view.findViewById(R.id.txt_unit);
            TextView txt_percent = view.findViewById(R.id.txt_percent);
            imageView.setImageResource(R.drawable.icon_s_gray);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams((DensityUtils.getWidth(getActivity()) - DensityUtils.dip2px(getActivity(), 20)) / 7,
                    DensityUtils.dip2px(getActivity(), 72));
            view.setLayoutParams(params);
            switch (i) {
                case 0:
                    txt_text1.setTextSize(Dimension.SP, 10);
                    txt_text1.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
                    txt_text1.setText(CommonUtils.subZeroAndDot(String.valueOf(contentObject.getEnergy())));
                    txt_text2.setVisibility(View.GONE);
                    txt_unit.setText(getResources().getString(R.string.kcal));
                    if (contentObject.getEnergyPercent() == 0.0d) {
                        txt_percent.setVisibility(View.GONE);
                        txt_text3.setText("n/a");
                    } else {
                        txt_text3.setText(String.valueOf(contentObject.getEnergyPercent()));
                    }
                    break;
                case 1:
                    txt_text1.setText(getResources().getString(R.string.protein));
                    txt_text2.setText(CommonUtils.subZeroAndDot(String.valueOf(contentObject.getProtein())));
                    txt_unit.setText("g");
                    if (contentObject.getProteinPercent() == 0.0d) {
                        txt_percent.setVisibility(View.GONE);
                        txt_text3.setText("n/a");
                    } else {
                        txt_text3.setText(String.valueOf(contentObject.getProteinPercent()));
                    }
                    break;
                case 2:
                    txt_text1.setText(getResources().getString(R.string.fat));
                    txt_text2.setText(CommonUtils.subZeroAndDot(String.valueOf(contentObject.getFat())));
                    txt_unit.setText("g");
                    if (contentObject.getFatPercent() == 0.0d) {
                        txt_percent.setVisibility(View.GONE);
                        txt_text3.setText("n/a");
                    } else {
                        txt_text3.setText(String.valueOf(contentObject.getFatPercent()));
                    }

                    if (contentObject != null) {
                        if (isFood) {
                            //食品的红绿灯分级，判断是否超标
                            if (fat <= 0.5) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (fat > 0.5 && fat <= 3) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (fat > 3 && fat <= 17.5) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (fat > 17.5) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        } else {
                            //饮料的红绿灯分级，判断是否超标
                            if (fat <= 0.5) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (fat > 0.5 && fat <= 1.5) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (fat > 1.5 && fat <= 8.75) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (fat > 8.75) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        }
                    }
                    break;
                case 3:
                    txt_text1.setText(getResources().getString(R.string.satfat));
                    txt_text2.setText(CommonUtils.subZeroAndDot(String.valueOf(contentObject.getSatFat())));
                    txt_unit.setText("g");
                    if (contentObject.getSatFatPercent() == 0.0d) {
                        txt_percent.setVisibility(View.GONE);
                        txt_text3.setText("n/a");
                    } else {
                        txt_text3.setText(String.valueOf(contentObject.getSatFatPercent()));
                    }

                    if (contentObject != null) {
                        if (isFood) {
                            //食品的红绿灯分级，判断是否超标
                            if (satFat <= 0.1) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (satFat > 0.1 && satFat <= 1.5) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (satFat > 1.5 && satFat <= 5) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (satFat > 5) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        } else {
                            //饮料的红绿灯分级，判断是否超标
                            if (satFat <= 0.1) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (satFat > 0.1 && satFat <= 0.75) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (satFat > 0.75 && satFat <= 8.75) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (satFat > 8.75) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        }
                    }
                    break;
                case 4:
                    txt_text1.setText(getResources().getString(R.string.carb));
                    txt_text2.setText(CommonUtils.subZeroAndDot(String.valueOf(contentObject.getCarbs())));
                    txt_unit.setText("g");
                    if (contentObject.getCarbsPercent() == 0.0d) {
                        txt_percent.setVisibility(View.GONE);
                        txt_text3.setText("n/a");
                    } else {
                        txt_text3.setText(String.valueOf(contentObject.getCarbsPercent()));
                    }
                    break;
                case 5:
                    txt_text1.setText(getResources().getString(R.string.sugar));
                    txt_text2.setText(CommonUtils.subZeroAndDot(String.valueOf(contentObject.getSugar())));
                    txt_unit.setText("g");
                    if (contentObject.getSugarPercent() == 0.0d) {
                        txt_percent.setVisibility(View.GONE);
                        txt_text3.setText("n/a");
                    } else {
                        txt_text3.setText(String.valueOf(contentObject.getSugarPercent()));
                    }

                    if (contentObject != null) {
                        if (isFood) {
                            //食品的红绿灯分级，判断是否超标
                            if (sugar <= 0.5) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (sugar > 0.5 && sugar <= 5) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (sugar > 5 && sugar <= 22.5) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (sugar > 22.5) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        } else {
                            //饮料的红绿灯分级，判断是否超标
                            if (sugar <= 0.5) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (sugar > 0.5 && sugar <= 2.5) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (sugar > 2.5 && sugar <= 11.25) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (sugar > 11.25) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        }
                    }
                    break;
                case 6:
                    txt_text1.setText(getResources().getString(R.string.sodium));
                    txt_text2.setText(CommonUtils.subZeroAndDot(String.valueOf(contentObject.getSodium())));
                    txt_unit.setText("mg");
                    if (contentObject.getSodiumPercent() == 0.0d) {
                        txt_percent.setVisibility(View.GONE);
                        txt_text3.setText("n/a");
                    } else {
                        txt_text3.setText(String.valueOf(contentObject.getSodiumPercent()));
                    }

                    if (contentObject != null) {
                        if (isFood) {
                            //食品的红绿灯分级，判断是否超标
                            if (sodium <= 5) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (sodium > 5 && sodium <= 120) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (sodium > 120 && sodium <= 600) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (sodium > 600) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        } else {
                            //饮料的红绿灯分级，判断是否超标
                            if (sodium <= 5) {
                                imageView.setImageResource(R.drawable.icon_s_blue);
                            } else if (sodium > 5 && sodium <= 120) {
                                imageView.setImageResource(R.drawable.icon_s_green);
                            } else if (sodium > 120 && sodium <= 300) {
                                imageView.setImageResource(R.drawable.icon_s_yellow);
                            } else if (sodium > 300) {
                                imageView.setImageResource(R.drawable.icon_s_red);
                            }
                        }
                    }
                    break;
                default:
            }
            linearLayout.addView(view);
        }
    }
    /**
     * 設置text文字
     * view_category;
     * view_origin;
     * view_taste;
     * view_tag;
     * view_ingredient;
     * view_allergen;
     * view_others;
     */
    private void setTitleTextView(ItemComparisonAdapter.HeaderHolder holder, List<String> contents, ItemProductInfoObject object) {
        int[] viewIDs = new int[]{R.id.view_category, R.id.view_origin, R.id.view_taste,
                R.id.view_allergen, R.id.view_ingredient,  R.id.view_others};
        ConstraintLayout[] layouts = new ConstraintLayout[]{
                holder.view_category,holder.view_origin,holder.view_taste,holder.view_allergen,holder.view_ingredient,
                holder.view_others};
        String[] strTexts = getResources().getStringArray(R.array.scan_specification_datas);
        for (int i = 0; i < viewIDs.length; i++) {
            findTitleTextView(layouts[i], viewIDs[i], strTexts[i], contents.get(i), object);
        }
    }

    /**
     * findContentTextView
     *
     * @param view
     * @param viewID
     * @param title
     */
    private void findTitleTextView(View view, int viewID, String title, String content, ItemProductInfoObject object) {
        View targetView = view.findViewById(viewID);
        TextView tv_title = targetView.findViewById(R.id.tv_title);
        tv_title.setText(title);

        switch (viewID) {
            case R.id.view_category:

            case R.id.view_ingredient:
            case R.id.view_others:
                TextView tv_content = targetView.findViewById(R.id.tv_content);
                tv_content.setText(content);
                break;
            case R.id.view_taste:
                FlowLayout fl_view4 = targetView.findViewById(R.id.fl_view);
                updateFlowView(fl_view4, object.getFeature());
                break;
            case R.id.view_origin:
                FlowLayout fl_view = targetView.findViewById(R.id.fl_view);
                updateFlowViewCoo(fl_view, object.getCOO());
                break;
            case R.id.view_tag:
                FlowLayout fl_view1 = targetView.findViewById(R.id.fl_view);
                updateFlowView(fl_view1, object.getTags());
                break;
            case R.id.view_allergen:
                FlowLayout fl_view2 = targetView.findViewById(R.id.fl_view);
                updateFlowView(fl_view2, object.getAllergen());
                break;
            default:
                break;
        }
    }
    /**
     * 更新流式佈局
     *
     * @param flowLayout
     * @param tags
     */
    private void updateFlowViewCoo(FlowLayout flowLayout, List<ProductTag> tags) {
        flowLayout.removeAllViews();

        /**
         * 添加佈局參數
         */
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(getActivity(), 30));
        params.rightMargin = DensityUtils.dip2px(getActivity(), 10);
        params.bottomMargin = DensityUtils.dip2px(getActivity(), 10);
        for (int i = 0; i < tags.size(); i++) {
            flowLayout.addView(updateFlowRowViewCOO(tags.get(i)), params);
        }
    }
    /**
     * 更新流式佈局
     *
     * @param flowLayout
     * @param tags
     */
    private void updateFlowView(FlowLayout flowLayout, List<ProductTag> tags) {
        flowLayout.removeAllViews();

        /**
         * 添加佈局參數
         */
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(getActivity(), 30));
        params.rightMargin = DensityUtils.dip2px(getActivity(), 10);
        params.bottomMargin = DensityUtils.dip2px(getActivity(), 10);
        for (int i = 0; i < tags.size(); i++) {
            flowLayout.addView(updateFlowRowView(tags.get(i)), params);
        }
    }
    /**
     * 添加item佈局
     */
    private View updateFlowRowViewCOO(ProductTag object) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_search_flow_row, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
        tv_text.setText(object.getName());
        tv_text.setOnClickListener(v -> {
//            Bundle bundle = new Bundle();
//            bundle.putString("CooName",object.getName());
//            bundle.putString(CommonConfig.CATEGORY_ID,object.getID());
            Bundle bundle = new Bundle();
            bundle.putString(CommonConfig.FEATURE_ID, String.valueOf(object.getID()));
            bundle.putString(CommonConfig.PRODUCT_SEARCH_TITLE, object.getName());
            openActivity(ItemFeatureActivity.class, bundle);
        });
        return view;
    }
    /**
     * 添加item佈局
     */
    private View updateFlowRowView(ProductTag object) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_search_flow_row, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
        tv_text.setText(object.getName());
        return view;
    }

    /**
     * 显示产品顶部数据
     */
    private void showProductHeaderData(ItemProductInfoObject object) {
//        GlideUtil.loadImageWithDefaultPlaceHolder(getActivity(), object.getIcon(), img_photo);
//        txt_title.setText(object.getBrandName());
//        txt_content.setText(object.getProductName());
//        txt_serving_size.setText(String.format(getResources().getString(R.string.per_serving_size), object.
//                getPackageSize(), object.getPackageUnit(), CommonUtils.subZeroAndDot(object.getServingSize()), object.getServingSizeUnit()));
//
//        /**
//         * 查看大图
//         */
//        img_photo.setOnClickListener(v -> {
//            List<PhotoObject> list = new ArrayList<>();
//            PhotoObject photoObject = new PhotoObject();
//            photoObject.setImageUrl(object.getIcon());
//            list.add(photoObject);
//            Bundle bundle = new Bundle();
//            bundle.putSerializable(CommonConfig.PHOTOLIST, (Serializable) list);
//            openActivityWithFadeInAnimation(ZoomPhotoActivity.class, bundle);
//        });
    }


    /**
     * 显示分类字符串
     *
     * @param category
     * @return
     */
    private String calculateCategoryString(ProductCategory category) {
        StringBuffer sb = new StringBuffer();
        if (!category.getName1().isEmpty()) {
            sb.append(category.getName1());
            sb.append(" > ");
        }
        if (!category.getName2().isEmpty()) {
            sb.append(category.getName2());
            sb.append(" > ");
        }
        if (!category.getName3().isEmpty()) {
            sb.append(category.getName3());
            sb.append(" > ");
        }
        if (!category.getName4().isEmpty()) {
            sb.append(category.getName4());
            sb.append(" > ");
        }
        sb.delete(sb.length() - 3, sb.length());
        return sb.toString();
    }
    /**
     * 获取产品规格详细数据
     */
    private void getProductInfoData(View view) {
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("ProductID", productID);
        params.put("Barcode", barCode);
        client.get(Cfg.BaseUrl + "/Product/GetProductInfo", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        try {
                            JSONObject jsonObject = new JSONObject(response.trim()).getJSONObject("Result");
                            infoObject = new Gson().fromJson(jsonObject.toString(), ItemProductInfoObject.class);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        initView(view);
                        adapter.notifyDataSetChanged();
                    }

                    public void Failure() {
                        super.Failure();
                    }

                });
    }
    private void getProductInfoObject(View view){
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("Barcode", barCode);
        params.put("ProductID", productID);
        client.get(Cfg.BaseUrl + "/Product/ProductInfo", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getContext()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        try {
                            JSONObject obj = new JSONObject(response.trim()).getJSONObject("Result");
                            if (obj !=null) {
                                itemProductDetailInfoObject = new Gson().fromJson(obj.toString(), ItemProductDetailInfoObject.class);


                                getProductInfoData(view);

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

//                        if (null != itemProductDetailInfoObject) {
//                            productID = itemProductDetailInfoObject.getProductID();
//                        }
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }
    /**
     * 获取产品含量
     */
    private void getProductContentData() {
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("Barcode", barCode);
        params.put("ProductID", productID);
        client.get(Cfg.BaseUrl + "/Product/Comparison", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                updateProductContentData(array);
                            } else {
                                ToastShow.displayToast(getActivity(), getResources().getString(R.string.finish_no_data));
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

    /**
     * updateProductContentData
     *
     * @param data
     */
    private void updateProductContentData(JSONArray data) {

        for (int i = 0; i < data.length(); i++) {
            try {
                JSONObject object = data.getJSONObject(i);
                ItemProductCompareObject itemProductCompareObject = new ItemProductCompareObject();
                itemProductCompareObject.setProductID(object.getString("ProductID"));
                itemProductCompareObject.setProductName(object.getString("ProductName"));
                itemProductCompareObject.setBrandName(object.getString("BrandName"));
                itemProductCompareObject.setCatName(object.getString("CatName"));
                itemProductCompareObject.setIcon(object.getString("Icon"));
                itemProductCompareObject.setFlavorName(object.getString("FlavorName"));
                itemProductCompareObject.setPackageSize(object.getString("PackageSize"));
                itemProductCompareObject.setServingSize(object.getString("ServingSize"));
                itemProductCompareObject.setValuePerUnit(object.getString("ValuePerUnit"));
                itemProductCompareObject.setPackageUnit(object.getString("PackageUnit"));
                itemProductCompareObject.setServingSizeUnit(object.getString("ServingSizeUnit"));
                itemProductCompareObject.setIsCollect(object.getInt("IsCollect"));
                itemProductCompareObject.setCategoryid(object.getInt("Categoryid"));
                itemProductCompareObject.setCategorylevel(object.getInt("Categorylevel"));
                if (object.has("Link"))
                    itemProductCompareObject.setLink(object.getString("Link"));
                itemProductCompareObject.setFood(object.getString("Type").equals("1") ? false : true);
                if (object.has("PerServing")) {
                    ProductContentObject contentObject1 = new ProductContentObject();
                    JSONObject object1 = object.getJSONObject("PerServing");
                    contentObject1.setEnergy(object1.getDouble("Energy"));
                    contentObject1.setProtein(object1.getDouble("Protein"));
                    contentObject1.setFat(object1.getDouble("Fat"));
                    contentObject1.setCarbs(object1.getDouble("Carbs"));
                    contentObject1.setSugar(object1.getDouble("Sugar"));
                    contentObject1.setSodium(object1.getDouble("Sodium"));
                    contentObject1.setSatFat(object1.getDouble("SatFat"));
                    contentObject1.setEnergyPercent(object1.getJSONObject("Percentage").getDouble("Energy"));
                    contentObject1.setProteinPercent(object1.getJSONObject("Percentage").getDouble("Protein"));
                    contentObject1.setFatPercent(object1.getJSONObject("Percentage").getDouble("Fat"));
                    contentObject1.setCarbsPercent(object1.getJSONObject("Percentage").getDouble("Carbs"));
                    contentObject1.setSugarPercent(object1.getJSONObject("Percentage").getDouble("Sugar"));
                    contentObject1.setSodiumPercent(object1.getJSONObject("Percentage").getDouble("Sodium"));
                    contentObject1.setSatFatPercent(object1.getJSONObject("Percentage").getDouble("SatFat"));
                    itemProductCompareObject.setPerServingObject(contentObject1);
                }

                if (object.has("Pergml")) {
                    ProductContentObject contentObject1 = new ProductContentObject();
                    JSONObject object1 = object.getJSONObject("Pergml");
                    contentObject1.setEnergy(object1.getDouble("Energy"));
                    contentObject1.setProtein(object1.getDouble("Protein"));
                    contentObject1.setFat(object1.getDouble("Fat"));
                    contentObject1.setCarbs(object1.getDouble("Carbs"));
                    contentObject1.setSugar(object1.getDouble("Sugar"));
                    contentObject1.setSodium(object1.getDouble("Sodium"));
                    contentObject1.setSatFat(object1.getDouble("SatFat"));
                    contentObject1.setEnergyPercent(object1.getJSONObject("Percentage").getDouble("Energy"));
                    contentObject1.setProteinPercent(object1.getJSONObject("Percentage").getDouble("Protein"));
                    contentObject1.setFatPercent(object1.getJSONObject("Percentage").getDouble("Fat"));
                    contentObject1.setCarbsPercent(object1.getJSONObject("Percentage").getDouble("Carbs"));
                    contentObject1.setSugarPercent(object1.getJSONObject("Percentage").getDouble("Sugar"));
                    contentObject1.setSodiumPercent(object1.getJSONObject("Percentage").getDouble("Sodium"));
                    contentObject1.setSatFatPercent(object1.getJSONObject("Percentage").getDouble("SatFat"));
                    itemProductCompareObject.setPergmlObject(contentObject1);
                }

                if (object.has("WholePack")) {
                    ProductContentObject contentObject1 = new ProductContentObject();
                    JSONObject object1 = object.getJSONObject("WholePack");
                    contentObject1.setEnergy(object1.getDouble("Energy"));
                    contentObject1.setProtein(object1.getDouble("Protein"));
                    contentObject1.setFat(object1.getDouble("Fat"));
                    contentObject1.setCarbs(object1.getDouble("Carbs"));
                    contentObject1.setSugar(object1.getDouble("Sugar"));
                    contentObject1.setSodium(object1.getDouble("Sodium"));
                    contentObject1.setSatFat(object1.getDouble("SatFat"));
                    contentObject1.setEnergyPercent(object1.getJSONObject("Percentage").getDouble("Energy"));
                    contentObject1.setProteinPercent(object1.getJSONObject("Percentage").getDouble("Protein"));
                    contentObject1.setFatPercent(object1.getJSONObject("Percentage").getDouble("Fat"));
                    contentObject1.setCarbsPercent(object1.getJSONObject("Percentage").getDouble("Carbs"));
                    contentObject1.setSugarPercent(object1.getJSONObject("Percentage").getDouble("Sugar"));
                    contentObject1.setSodiumPercent(object1.getJSONObject("Percentage").getDouble("Sodium"));
                    contentObject1.setSatFatPercent(object1.getJSONObject("Percentage").getDouble("SatFat"));
                    itemProductCompareObject.setWholePackObject(contentObject1);
                }

                if (object.has("ProductImageList")) {
                    JSONArray array = object.getJSONArray("ProductImageList");
                    if (array.length() > 0) {
                        List<PhotoObject> photoObjects = new ArrayList<>();
                        for (int j = 0; j < array.length(); j++) {
                            JSONObject object1 = array.getJSONObject(j);
                            PhotoObject photoObject = new PhotoObject();
                            photoObject.setImageUrl(object1.getString("ImageUrl"));
                            photoObjects.add(photoObject);
                        }
                        itemProductCompareObject.setProductImageList(photoObjects);
                    }
                }
                headerList.add(itemProductCompareObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        /**
         * 获取产品相似列表
         */
        if (!headerList.isEmpty()) {
            headerItemProductCompareObject = headerList.get(0);
            getProductSimilarData(headerItemProductCompareObject.getProductID());
        }

    }

    /**
     * getProductSimilarData
     * 获取产品对比列表
     */
    private void getProductSimilarData(String productID) {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        params.put("Type", type);
        params.put("ProductID", productID);
        params.put("IsEnergy", isEnergy);
        params.put("IsProtein", isProtein);
        params.put("IsFat", isFat);
        params.put("IsSatFat", isSatFat);
        params.put("IsCarb", isCarb);
        params.put("IsSugar", isSugar);
        params.put("IsSodium", isSodium);
        params.put("Optionids", optionIds);
        client.get(Cfg.BaseUrl + "/Product/Similar", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();

                        if (!list.isEmpty() && list.size() > 0) {
                            list.clear();
                        }
                        //添加头部
                        list.add(new ItemProductCompareObject());

                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                /**
                                 * 加载数据
                                 */
                                updateProductSimilarData(array);
                            } else {
                                adapter.notifyDataSetChanged();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

    /**
     * updateProductSimilarData
     *
     * @param data
     */
    private void updateProductSimilarData(JSONArray data) {
        for (int i = 0; i < data.length(); i++) {
            try {
                JSONObject object = data.getJSONObject(i);
                ItemProductCompareObject compareObject = new ItemProductCompareObject();
                compareObject.setProductID(object.getString("ProductID"));
                compareObject.setProductName(object.getString("ProductName"));
                compareObject.setBrandName(object.getString("BrandName"));
                compareObject.setCatName(object.getString("CatName"));
                compareObject.setIcon(object.getString("Icon"));
                compareObject.setFlavorName(object.getString("FlavorName"));
                compareObject.setPackageSize(object.getString("PackageSize"));
                compareObject.setServingSize(object.getString("ServingSize"));
                compareObject.setValuePerUnit(object.getString("ValuePerUnit"));
                compareObject.setPackageUnit(object.getString("PackageUnit"));
                compareObject.setServingSizeUnit(object.getString("ServingSizeUnit"));
                compareObject.setIsCollect(object.getInt("IsCollect"));
                if (object.has("Link"))
                    compareObject.setLink(object.getString("Link"));

                if (object.has("Pergml")) {
                    ProductContentObject contentObject1 = new ProductContentObject();
                    JSONObject object1 = object.getJSONObject("Pergml");
                    contentObject1.setEnergy(object1.getDouble("Energy"));
                    contentObject1.setProtein(object1.getDouble("Protein"));
                    contentObject1.setFat(object1.getDouble("Fat"));
                    contentObject1.setCarbs(object1.getDouble("Carbs"));
                    contentObject1.setSugar(object1.getDouble("Sugar"));
                    contentObject1.setSodium(object1.getDouble("Sodium"));
                    contentObject1.setSatFat(object1.getDouble("SatFat"));
                    contentObject1.setEnergyPercent(object1.getJSONObject("Percentage").getDouble("Energy"));
                    contentObject1.setProteinPercent(object1.getJSONObject("Percentage").getDouble("Protein"));
                    contentObject1.setFatPercent(object1.getJSONObject("Percentage").getDouble("Fat"));
                    contentObject1.setCarbsPercent(object1.getJSONObject("Percentage").getDouble("Carbs"));
                    contentObject1.setSugarPercent(object1.getJSONObject("Percentage").getDouble("Sugar"));
                    contentObject1.setSodiumPercent(object1.getJSONObject("Percentage").getDouble("Sodium"));
                    contentObject1.setSatFatPercent(object1.getJSONObject("Percentage").getDouble("SatFat"));
                    compareObject.setPergmlObject(contentObject1);
                }

                if (object.has("ProductImageList")) {
                    JSONArray array = object.getJSONArray("ProductImageList");
                    if (array.length() > 0) {
                        List<PhotoObject> photoObjects = new ArrayList<>();
                        for (int j = 0; j < array.length(); j++) {
                            JSONObject object1 = array.getJSONObject(j);
                            PhotoObject photoObject = new PhotoObject();
                            photoObject.setImageUrl(object1.getString("ImageUrl"));
                            photoObjects.add(photoObject);
                        }
                        compareObject.setProductImageList(photoObjects);
                    }
                }
                list.add(compareObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        //刷新数据
        adapter.notifyDataSetChanged();
    }

    /**
     * 更新选中的标签view
     *
     * @param linear_filter_view
     * @param list
     */
    private void updateFilterCategoryView(LinearLayout linear_filter_view, List<OptionLevel3Object> list) {
        linear_filter_view.removeAllViews();

        /**
         * 添加佈局參數
         */
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, DensityUtils.dip2px(getActivity(), 37));
        params.rightMargin = DensityUtils.dip2px(getActivity(), 6);
        for (int i = 0; i < list.size(); i++) {
            linear_filter_view.addView(updateFilterCategoryRowView(list, list.get(i)), params);
        }
    }

    /**
     * @param list
     * @param object
     * @return
     */
    private View updateFilterCategoryRowView(List<OptionLevel3Object> list, OptionLevel3Object object) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.item_product_filter_category_with_delete_row, null);
        TextView tv_text = view.findViewById(R.id.tv_text);
        ImageView iv_delete = view.findViewById(R.id.iv_delete);
        tv_text.setText(object.getOptionName());
        iv_delete.setOnClickListener(v -> {
            list.remove(object);
            headerItemProductCompareObject.setOptionLevel3ObjectList(list);
            filterProductSimilarData(headerItemProductCompareObject.getProductID(), list);
        });
        return view;
    }

    /**
     * 获取一般筛选id的产品相关列表
     *
     * @param productID
     * @param level3ObjectList
     */
    private void filterProductSimilarData(String productID, List<OptionLevel3Object> level3ObjectList) {
        /**
         * 获取选中的筛选ID
         */
        StringBuffer sb = new StringBuffer();
        for (OptionLevel3Object object : level3ObjectList) {
            sb.append(object.getOptionID());
            sb.append(",");
        }
        if (sb.length() > 0) {
            optionIds = sb.deleteCharAt(sb.length() - 1).toString();
        } else {
            optionIds = "";
        }

        /**
         * 刷新数据
         */
        isFirstHeader = true;
        getProductSimilarData(productID);
    }

    /**
     * 接收EventBus
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /**
         * 接收选中的筛选数据
         */
        if (event.getEvent().equals(CommonConfig.OPTION_LIST)) {
            List<OptionLevel3Object> level3ObjectList = event.getOptionLevel3ObjectList();
            headerItemProductCompareObject.setOptionLevel3ObjectList(level3ObjectList);
            filterProductSimilarData(headerItemProductCompareObject.getProductID(), level3ObjectList);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);

        /**
         * 保存筛选记录，下一次进入页面时默认筛选
         */
        Cfg.change("isEnergy", isEnergy);
        Cfg.change("isProtein", isProtein);
        Cfg.change("isFat", isFat);
        Cfg.change("isSatFat", isSatFat);
        Cfg.change("isCarb", isCarb);
        Cfg.change("isSugar", isSugar);
        Cfg.change("isSodium", isSodium);
        Cfg.save();
    }
}
